package com.ironman.compute.consumer;

import com.ironman.common.params.HeartrateParam;
import com.ironman.common.util.AccuracyUtil;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;

import java.util.function.Consumer;

@Slf4j
public class HeartrateConsumer extends BaseConsumer implements Consumer<ONode> {

    private Double preHeartrate = null;

    private final HeartrateParam heartrateParam;

    public HeartrateConsumer(HeartrateParam heartrateParam, SysTrainingProperties sysTrainingProperties, MqttClient mqttClient) {
        super(sysTrainingProperties, mqttClient);
        this.heartrateParam = heartrateParam;
    }

    @Override
    public void accept(ONode data) {
        String hrType = data.select("hrType").getString();
        doAccept("heartrate/" + hrType, data, (topic, dataJson, published) -> log.info("{} {} \n{}", topic, published, dataJson));
    }

    @Override
    public boolean threshold(ONode data) {
        String hrType = data.select("hrType").getString();
        double heartrate = data.select("hr").getDouble();

        if (preHeartrate == null) {
            getCounter().incrementAndGet();
            preHeartrate = heartrate;
            data.set("tt", "t");
            return true;
        }

        Integer heartrateThreshold = heartrateParam.getHeartrateThreshold();
        double diffHeartrate = Math.abs(heartrate - preHeartrate);
        if (diffHeartrate > heartrateThreshold) {
            getCounter().set(0);
            log.info("{} 心率触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", hrType, heartrateThreshold, heartrate, preHeartrate, diffHeartrate);
            preHeartrate = heartrate;
            data.set("tt", "t");
            return true;
        }

        Integer countThreshold = heartrateParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.info("{} 心率触发数量阈值: {} ", hrType, countThreshold);
            preHeartrate = heartrate;
            data.set("tt", "c");
            return true;
        }
        return false;
    }

    @Override
    public void precision(ONode data) {
        double heartrate = data.select("hr").getDouble();
        data.set("hr", AccuracyUtil.downHeartrateInteger(heartrate));
    }
}
